package com.self.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class MyThreadPool {

    public static ExecutorService createFixedThreadPool(int size) {
//        return Executors.newFixedThreadPool(size);
        return Executors.newFixedThreadPool(size, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("XXXX" + thread.getId());
                return thread;
            }
        });
    }


    public static void main(String[] args) {
        final CountDownLatch countDownLatch = new CountDownLatch(5);
        ExecutorService executorService = MyThreadPool.createFixedThreadPool(5);

        for (int i=0; i <10; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("name:" + Thread.currentThread().getName());
                    countDownLatch.countDown();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
    }
}
